package com.test.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONSerializer;

import com.test.data.DataSource;
import com.test.dto.VehicleInfoDTO;

@WebServlet("/getVehicleInfo")
public class GetVehicleInfo extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
    public GetVehicleInfo() 
    {
        super();
    }
    

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		try {
			response.setContentType("application/json");
			PrintWriter out = response.getWriter();
			Connection connection = DataSource.getConnection();
			PreparedStatement pstmt = connection.prepareStatement("SELECT * FROM VEHICLEINFO");
			ResultSet resultSet = pstmt.executeQuery();
			List<VehicleInfoDTO> vehicleInfoDTOs = new ArrayList<VehicleInfoDTO>(); 
			while(resultSet.next())
			{
				VehicleInfoDTO vehicleInfoDTO = new VehicleInfoDTO();
				vehicleInfoDTO.setId(resultSet.getString(1));
				vehicleInfoDTO.setVehicleName(resultSet.getString(2));
				vehicleInfoDTO.setVehicleNo(resultSet.getString(3));
				vehicleInfoDTO.setIconCls(resultSet.getString(4));
				vehicleInfoDTO.setVehicleImei(resultSet.getString(5));
				vehicleInfoDTO.setText(resultSet.getString(2)+" - "+resultSet.getString(3));
				vehicleInfoDTOs.add(vehicleInfoDTO);
			}
			out.write(""+JSONSerializer.toJSON(vehicleInfoDTOs));
			out.flush();
			out.close();
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
